# -*- coding: utf-8 -*-
from django.db import models


class User(models.Model):
    creation_datetime = models.DateTimeField(u'Создан', auto_now_add=True, editable=False)
    login = models.EmailField(u'Логин (e-mail)')
    password_hash = models.CharField(max_length=255, editable=False)
    name = models.CharField(u'Имя', max_length=255, blank=True, null=True)
    description = models.TextField(u'Информация', blank=True, null=True)

    def __unicode__(self):
        if self.name:
            return u'%s (%s)' % (self.name, self.login)
        else:
            return self.login

    class Meta:
        ordering = ('login',)
        verbose_name = u'пользователь'
        verbose_name_plural = u'пользователи'


class Project(models.Model):
    is_archive = models.BooleanField(u'Архивный')
    creation_datetime = models.DateTimeField(u'Создан', auto_now_add=True, editable=False)
    owner = models.ForeignKey(User)
    name = models.CharField(u'Название', max_length=255)
    description = models.TextField(u'Описание', blank=True, null=True)
    access = models.ManyToManyField(User, verbose_name=u'Право имеющие', related_name='access')

    def __unicode__(self):
        return self.name

    class Meta:
        ordering = ('name',)
        verbose_name = u'проект'
        verbose_name_plural = u'проекты'



class AbstractProperty(models.Model):
    order = models.IntegerField(u'Порядок', default=0)
    name = models.CharField(u'Название', max_length=255)
    is_default = models.BooleanField(u'По умолчанию')
    
    @classmethod
    def _defaults(cls):
        return list(cls.objects.filter(is_default=True))
    
    def save(self, *args, **kwargs):
        dont_check = kwargs.pop('dont_check', False) 
        if not dont_check:
            defaults = self._defaults()
            if self.is_default:
                # drop all other
                for obj in defaults:
                    if obj.pk == self.pk:
                        continue
                    obj.is_default = False
                    obj.save(dont_check=True)            
            else:
                if not defaults:                
                    self.is_default = True
                else:                
                    defaults.pop()
                    for obj in defaults:
                        obj.is_default = False
                        obj.save(dont_check=True)
        return super(AbstractProperty, self).save(*args, **kwargs)

    def __unicode__(self):
        return self.name

    class Meta:
        abstract = True
        ordering = ('order',)
        verbose_name = u'приоритет'
        verbose_name_plural = u'приоритеты'


class Priority(AbstractProperty):
    class Meta(AbstractProperty.Meta):
        verbose_name = u'приоритет задачи'
        verbose_name_plural = u'приоритеты задачи'


class Category(AbstractProperty):
    class Meta(AbstractProperty.Meta):
        verbose_name = u'категория задачи'
        verbose_name_plural = u'категории задачи'


class Reason(AbstractProperty):
    class Meta(AbstractProperty.Meta):
        verbose_name = u'причина закрытия'
        verbose_name_plural = u'причины закрытия'


class Task(models.Model):
    #start_time = models.DateTimeField(auto_now_add=True)
    project = models.ForeignKey(Project, verbose_name=u'Проект')
    parent = models.ForeignKey('self', null=True, blank=True)
    creation_datetime = models.DateTimeField(u'Создана', auto_now_add=True, editable=False)    
    author = models.ForeignKey(User, verbose_name='Постановщик', related_name='owner')
    executor = models.ForeignKey(User, null=True, blank=True, verbose_name='Исполнитель', related_name='exceutor')
    name = models.CharField(u'Задача', max_length=255)
    description = models.TextField(u'Описание', blank=True, null=True)
    priority = models.ForeignKey(Priority, verbose_name=u'Приоритет',
        default=lambda: Priority.objects.get(is_default=True) or None )
    category = models.ForeignKey(Category, verbose_name=u'Категория',
        default=lambda: Category.objects.get(is_default=True) or None )
    close_datetime = models.DateTimeField(u'Завершена', null=True, blank=True)
    close_reason = models.ForeignKey(Reason, verbose_name=u'Причина закрытия', blank=True, null=True)
    approve_datetime = models.DateTimeField(u'Одобрена', null=True, blank=True)

    def number(self):
        return '%04d' % self.id

    def is_closed(self):
        return bool(self.close_datetime)
#
#    def get_timedelta(self):
#        if self.stop_time:
#            return self.stop_time - self.start_time
#        else:
#            return datetime.now() - self.start_time

    def save(self, *args, **kwargs):
        self.description = self.description.strip()
        if not self.executor:
            self.close_datetime = None
            self.close_reason = None
            self.approve_datetime = None
        return super(Task, self).save(*args, **kwargs)

    def __unicode__(self):
        return u'#%s - %s' % (self.id, self.name)

    class Meta:
        verbose_name = u'задача'
        verbose_name_plural = u'задачи'
        ordering = ('-creation_datetime',)


class Comment(models.Model):
    parent = models.ForeignKey('self', null=True, blank=True)
    creation_datetime = models.DateTimeField(u'Создан', auto_now_add=True, editable=False)
    task = models.ForeignKey(Task)
    author = models.ForeignKey(User)
    text = models.TextField(u'Текст')
    #file = models.FileField(verbose_name, name, upload_to, storage)

    def __unicode__(self):
        return self.text
    
    class Meta:
        verbose_name = u'камент'
        verbose_name_plural = u'каменты'
        ordering = ('-creation_datetime',)
        
        